import logging
import os
from flask import Flask

def create_app(config_name=None):
    """Flask应用工厂函数"""
    
    # 明确指定模板目录和静态文件目录
    template_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates')
    static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static')
    app = Flask(__name__, template_folder=template_dir, static_folder=static_dir, static_url_path='/static')
    
    # 加载配置
    if config_name is None:
        config_name = os.environ.get('FLASK_ENV') or 'default'
    
    from config import config
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    
    # 配置日志
    if not app.debug and not app.testing:
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
        )
    
    # 注册蓝图
    from app.routes import main_bp, api_bp
    app.register_blueprint(main_bp)
    app.register_blueprint(api_bp, url_prefix='/api')
    
    # 初始化服务
    from app.services import directory_scanner, image_processor, cache_manager
    directory_scanner.init_app(app)
    image_processor.init_app(app)
    cache_manager.init_app(app)
    
    # 应用启动时扫描漫画
    with app.app_context():
        try:
            directory_scanner.scan_comics()
            app.logger.info("应用启动时漫画扫描完成")
        except Exception as e:
            app.logger.error(f"应用启动时漫画扫描失败: {e}")
    
    return app